package com.hunan.api.catv.service.impl.function.remote;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangchao
 * @date 2021-04-26 10:19 上午
 */
@Service
public class RemoteControlService {

    public static Logger log = LoggerFactory.getLogger(RemoteControlService.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 遥控器登录授权获取token
     */
    public String getAccessToken(String domain, Map<String, String> body) {
        String accessToken = (String) redisUtils.get(CacheName.remoteToken);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/system/auth");
        HttpEntity<String> request = new HttpEntity<String>(GsonUtils.toJson(body), getHeaderByJson(accessToken));
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url.toString(), request, String.class);
        } catch (RestClientException e) {
            log.error("对接遥控器获取token失败:{}", e);
        }
        if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
            JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
            if (HttpStatus.OK.value() == jsonObject.get("code").getAsInt()) {
                accessToken = jsonObject.get("data").getAsString();
                redisUtils.set(CacheName.remoteToken, accessToken, 7200);
            }
        }
        return accessToken;
    }

    /**
     * 绑定设备
     */
    public JsonObject bindEquipment(String domain, HashMap<String, String> map, String accessToken) {
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/user/bind");
        HttpEntity<String> request = new HttpEntity<String>(GsonUtils.toJson(map), getHeaderByJson(accessToken));
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url.toString(), request, String.class);
            if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
                JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
                return jsonObject;
            }
        } catch (RestClientException e) {
            log.error("对接遥控器绑定设备失败:{}，参数:{}", e, map);
        }
        return null;
    }

    /**
     * 解绑设备
     */
    public JsonObject untieEquipment(String domain, String phone, String accessToken) {
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/user/unbind");
        JsonObject bindJson = getBindEquipmentByUserPhone(domain, accessToken, phone);
        if(bindJson == null){
            return null;
        }
        HashMap<String, String> map = new HashMap<>(16);
        map.put("id",bindJson.get("id").getAsString());
        map.put("userId",bindJson.get("userId").getAsString());
        HttpEntity<String> request = new HttpEntity<String>(GsonUtils.toJson(map), getHeaderByJson(accessToken));
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url.toString(), request, String.class);
            if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
                JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
                return jsonObject;
            }
        } catch (RestClientException e) {
            log.error("对接遥控器绑定设备失败:{}，参数:{}", e, map);
        }
        return null;
    }


    /**
     * 通过手机号获取用户绑定设备
     */
    public JsonObject getBindEquipmentByUserPhone(String domain, String accessToken, String phone) {
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/user/queryBind");
        url.append("?userId={userId}");
        HttpEntity<String> request = new HttpEntity<String>("", getHeader(accessToken));
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.exchange(url.toString(), HttpMethod.GET, request, String.class, phone);
            if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
                JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
                if (HttpStatus.OK.value() == jsonObject.get("code").getAsInt()) {
                    JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonObject json = jsonArray.get(i).getAsJsonObject();
                        if (json.get("state").getAsInt() == 1) {
                            return json;
                        }
                    }
                }
            }
        } catch (RestClientException e) {
            log.error("对接遥控器获取用户绑定设备失败:{}，参数:{}", e, phone);
        }
        return null;
    }

    /**
     * 遥控器指令
     * 序号	指令描述	键值
     * 1	数字0	48
     * 2	数字1	49
     * 3	数字2	50
     * 4	数字3	51
     * 5	数字4	52
     * 6	数字5	53
     * 7	数字6	54
     * 8	数字7	55
     * 9	数字8	56
     * 10	数字9	57
     * 11	音量+	447
     * 12	音量-	448
     * 13	静音	    449
     * 14	返回	    640
     * 15	确认	    13
     * 16	电源	    88
     * 17	上	    38
     * 18	下	    40
     * 19	左	    37
     * 20	右	    39
     * 21	频道+	17
     * 22	频道-	18
     * 23	菜单	    36
     * 24	首页	    468
     */
    public JsonObject controlPushByCode(String domain, HashMap<String, String> map, String accessToken) {
        int count = 0;
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/im/control");
        HttpEntity<String> request = new HttpEntity<String>(GsonUtils.toJson(map), getHeaderByJson(accessToken));
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url.toString(), request, String.class);
            if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
                JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
                return jsonObject;
            }
        } catch (RestClientException e) {
            log.error("对接遥控器指令失败:{}，参数:{}", e, map);
        } finally {
            if (response == null) {
                while (count < 3) {
                    JsonObject jsonObject = controlPushByCode(domain, map, accessToken);
                    if (jsonObject != null) {
                        return jsonObject;
                    }
                    count++;
                }
            }
        }
        return null;
    }

    public HttpHeaders getHeaderByJson(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (StringUtils.isNotBlank(token)) {
            headers.add("access_token", token);
        }
        return headers;
    }

    public HttpHeaders getHeader(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        if (StringUtils.isNotBlank(token)) {
            headers.add("access_token", token);
        }
        return headers;
    }

    public static void main(String[] args) {
        String domain = "http://tymzdphd.hunancatv.com:3308";

        //String userId = "583";
        StringBuffer url = new StringBuffer(domain);
        url.append("/hnyx-wxtv/user/queryBind");
        url.append("?userId=18774044985");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        headers.add("access_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsiZ2puNFVxTjV6YVh3RVBMbCIsIuicl-eJm0FwcCJdfQ.O1_iR8gCSGy8GqrpphhCaf9XS28-awPznKJJSDVEvLU");
        HttpEntity<String> request = new HttpEntity<String>("", headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.exchange(url.toString(), HttpMethod.GET, request, String.class, "18774044985");
            if (response.getStatusCodeValue() == HttpStatus.OK.value()) {
                JsonObject jsonObject = GsonUtils.fromJson(response.getBody(), JsonObject.class);
                if (HttpStatus.OK.value() == jsonObject.get("code").getAsInt()) {
                    JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonObject json = jsonArray.get(i).getAsJsonObject();
                        if (json.get("state").getAsInt() == 1) {
                            log.info("{}", json);                        }
                    }
                }
            }
        } catch (RestClientException e) {
            //log.error("对接遥控器绑定设备失败:{}，参数:{}", e, map);
        }
    }
}
